package com.paradogs.framework.utils;

import org.hibernate.validator.HibernateValidator;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.util.Set;
import java.util.stream.Collectors;

public class ValidUtils {

    private static final Validator VALIDATOR;

    static {
        ValidatorFactory factory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .buildValidatorFactory();
        VALIDATOR = factory.getValidator();
    }

    /**
     * 校验对象并返回注解中定义的错误消息（多个错误用逗号分隔）
     * @param object 待校验对象
     * @return 错误消息（无错误返回空字符串）
     */
    public static <T> String validate(T object) {
        if (object == null) return "校验对象不能为空";
        Set<ConstraintViolation<T>> violations = VALIDATOR.validate(object);
        if (violations.isEmpty()) return "";
        return violations.stream()
                .map(v -> v.getMessage()) // 直接返回注解中的 message
                .collect(Collectors.joining(", "));
    }

    /**
     * 快速校验（失败时抛出异常，异常消息为注解中的内容）
     */
    public static <T> void validateOrThrow(T object) {
        String errorMsg = validate(object);
        if (!errorMsg.isEmpty()) {
            throw new jakarta.validation.ValidationException(errorMsg);
        }
    }
}
